package com.sctvcloud.zhaohua_sd.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.mob.tools.utils.DeviceHelper;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.GroupOrderHelperSingled;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.ADynamicsItem;
import com.sctvcloud.zhaohua_sd.beans.AdvertBean;
import com.sctvcloud.zhaohua_sd.beans.AdvertDataVo;
import com.sctvcloud.zhaohua_sd.beans.FUsers;
import com.sctvcloud.zhaohua_sd.beans.FocusColumn;
import com.sctvcloud.zhaohua_sd.beans.HomeListItem;
import com.sctvcloud.zhaohua_sd.beans.HomeLive;
import com.sctvcloud.zhaohua_sd.beans.HomePopular;
import com.sctvcloud.zhaohua_sd.beans.LiveItem;
import com.sctvcloud.zhaohua_sd.beans.NewsClickCountBean;
import com.sctvcloud.zhaohua_sd.beans.NewsDate;
import com.sctvcloud.zhaohua_sd.beans.NewsIdBean;
import com.sctvcloud.zhaohua_sd.beans.NewsItem;
import com.sctvcloud.zhaohua_sd.beans.NewsListClickRequestBean;
import com.sctvcloud.zhaohua_sd.beans.NewsListClickVo;
import com.sctvcloud.zhaohua_sd.beans.SingleResult;
import com.sctvcloud.zhaohua_sd.beans.Titles;
import com.sctvcloud.zhaohua_sd.http.AbsListNetCallback;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.activities.CommodityDetailActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.FloatAdActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.LoginActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.NewesDetailActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.TYFOH5Activity;
import com.sctvcloud.zhaohua_sd.ui.adapter.AnchorHomePageAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.GreatestAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.holder.HomeHotVideoHolder;
import com.sctvcloud.zhaohua_sd.ui.adapter.holder.HomeLiveHolder;
import com.sctvcloud.zhaohua_sd.ui.adapter.holder.HomeSpecialHolder;
import com.sctvcloud.zhaohua_sd.ui.util.IListShowData;
import com.sctvcloud.zhaohua_sd.ui.util.NewsDateComparator;
import com.sctvcloud.zhaohua_sd.ui.utils.GlideUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.MutilDateNewsGetHelper;
import com.sctvcloud.zhaohua_sd.ui.utils.SkipUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.UIUtils;
import com.sctvcloud.zhaohua_sd.ui.widget.BasePlayerView;
import com.sctvcloud.zhaohua_sd.utils.ListTypeUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class GreatestFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener, HomeSpecialHolder.OnSpecialSelectMoreListener, HomeLiveHolder.OnLivePlayingListener, HomeHotVideoHolder.OnHotVideoSelectListener {
    public static final String FLOAT_AD_SHOW = "is_float_ad_show";
    private static final int CODE_REQUEST_LOGIN = 1;
    private static final int WHAT_GET_EXPRESS = 551;
    private static final long SPACE_GET_EXPRESS = 60000L;
    private static final int WHAT_GET_CLOSE_FAD = 100;
    @BindView(R.id.common_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    @BindView(R.id.ad_layer_layout)
    protected RelativeLayout adLayerLayout;
    @BindView(R.id.ad_layer)
    protected ImageView adLayer;
    @BindView(R.id.close_ad)
    protected ImageView adClose;


    private LinearLayoutManager layoutManager;
    private GreatestAdapter adapter;


    private GroupOrderHelperSingled groupOrderHelper;

    private String hour24UrlTemp, bannerUrlTemp, liveUrlTemp, expressUrlTemp, popularUrlTemp, specialUrlTemp, anchorsUrlTemp, promoteUrl;
    private int current24Page = -1, secTitlePos = -1;
    private Date first24TitleDateTemp;

    private MutilDateNewsGetHelper hour24GetHelper;
    private int newsFlashType = 0;
    private List<IListShowData> newsList = new ArrayList<>();
    private boolean isReset;
    private String news24Domain = "";
    private Handler handler;

    //    private LittleLifeManager littleLifeManager;

    private long lastGetTime = -1;
    private boolean isFirst = false;
    private String selectedCityName = "";
    private int newKey = GreatestAdapter.VIEWTYPE_NEWS_24;
    private boolean isRefresh = false;
    private long dyHeight = 0;
    private AdvertBean bottomAdBean;//精选底部广告
    private AdvertBean footprintAdBean;//脚图广告
    private Animation mIntoAction;
    private Animation mOutAction;
    private Animation mFootprintIntoAction;
    private Animation mFootprintOutAction;
    private CountDownTimer timer;//脚图广告定时关闭


    private List<IListShowData> newsItems;//用于新闻评论数据的处理

    private List<IListShowData> greatList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isFirst = (boolean) SharedPreferencesUtil.getParam(getActivity(), FLOAT_AD_SHOW, false);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null) {
                    parseMsg(msg);
                }
            }
        };

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_greatest, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isThisShowing()) {
            refreshPlayer();
            //JLog.e("HomeLiveHolder play onResume  ");
        }
//        initLiveStatus();
//        JLog.e("okh  parent=" + isParentShowing + "  this=" + isThisShowing + "  count=" + getShowCount() + "  front=" + isFront);
    }


    @Override
    public void onRefresh() {
        releaseLive();
        //JLog.e("HomeLiveHolder play onRefresh  ");
        if (Cache.getInstance().isCityShow()) {
            String news24Url = Cache.getInstance().getChoosedCityNewsUrl();
            news24Domain = UIUtils.getDomain(news24Url);
        } else {
            news24Domain = "";
        }
        greatList.clear();
        isRefresh = true;
        //首次加载数据，或之后下拉刷新
        getChannelList();
    }

    @Override
    public void onLoadMore() {
        if (Cache.getInstance().isCityShow()) {
            String news24Url = Cache.getInstance().getChoosedCityNewsUrl();
            news24Domain = UIUtils.getDomain(news24Url);
        } else {
            news24Domain = "";
        }
        if (groupOrderHelper.getCount() <= 0) {
            getNews24Page(news24Domain, false);
        } else {
            if (refreshLayout.isRefreshing()) {
                refreshLayout.loadMoreComplete();
            }
        }
    }

    private MutilDateNewsGetHelper init24Helper() {
        if (hour24GetHelper == null) {
            hour24GetHelper = new MutilDateNewsGetHelper(this);
            hour24GetHelper.setShouldSetTitleAfter(true);
        }
        return hour24GetHelper;
    }

    /**
     * 下拉刷新时释放正在直播的内容
     */
    private void releaseLive() {
        if (null != adapter) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            for (int i = 0; i < adapter.getItemCount(); i++) {
                View topView = layoutManager.findViewByPosition(i);
                if (null != topView && recyclerView.getChildViewHolder(topView) instanceof HomeLiveHolder) {
                    HomeLiveHolder liveHolder = (HomeLiveHolder) recyclerView.getChildViewHolder(topView);
                    liveHolder.onIDestory();
                    break;
                }
            }
        }
    }

    /**
     * 暂停正在直播的内容
     */
    private void pauseLive() {
        if (null != adapter) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            for (int i = 0; i < adapter.getItemCount(); i++) {
                View topView = layoutManager.findViewByPosition(i);
                if (null != topView && recyclerView.getChildViewHolder(topView) instanceof HomeLiveHolder) {
                    HomeLiveHolder liveHolder = (HomeLiveHolder) recyclerView.getChildViewHolder(topView);
                    liveHolder.onIPause();
                    break;
                }
            }
        }
    }

    /**
     * 重新初始化一下直播播放器设置
     */
    private void refreshPlayer() {
        if (null != adapter) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            for (int i = 0; i < adapter.getItemCount(); i++) {
                View topView = layoutManager.findViewByPosition(i);
                if (null != topView && recyclerView.getChildViewHolder(topView) instanceof HomeLiveHolder) {
                    HomeLiveHolder liveHolder = (HomeLiveHolder) recyclerView.getChildViewHolder(topView);
                    JLog.e("-HomeLiveHolder-refreshPlayer---");
                    liveHolder.onIResume();
                    liveHolder.onPrepared();
                    break;
                }
            }
        }
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        groupOrderHelper = new GroupOrderHelperSingled();
        adLayerLayout.setVisibility(View.GONE);
        adClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adLayerLayout.setVisibility(View.GONE);
                adLayerLayout.startAnimation(mOutAction);
                Cache.getInstance().setHomeGreateAdClosed(true);
            }
        });
        adLayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 底部广告跳转
                if (null != bottomAdBean) {
                    if (bottomAdBean.getAdType() == 1) {
                        //新闻
                        if (ListUtils.isListValued(bottomAdBean.getNewsUrlList())) {
                            Intent intent = new Intent(getContext(), NewesDetailActivity.class);
                            intent.putExtra(BaseActivity.EX_URL, bottomAdBean.getNewsUrlList().get(0).getNewsUrl());
                            startActivity(intent);
                        }
                        adLayerLayout.setVisibility(View.GONE);
                        adLayerLayout.startAnimation(mOutAction);
                        Cache.getInstance().setHomeGreateAdClosed(true);
                    } else if (bottomAdBean.getAdType() == 2) {
                        //商品广告
                        if (null != UserManager.getInstance().getUser()) {
                            String url = bottomAdBean.getProductUrl();
                            String json = bottomAdBean.getProductJson();
                            if (bottomAdBean.getProductType().equalsIgnoreCase("1")) {
                                CommodityDetailActivity.StartThis(getActivity(), url, json);
                            } else if (bottomAdBean.getProductType().equalsIgnoreCase("2")) {
                                Intent intent = new Intent(getContext(), TYFOH5Activity.class);
                                intent.putExtra(TYFOH5Activity.HTML_URL, url);
                                startActivity(intent);
                            }
                            adLayerLayout.setVisibility(View.GONE);
                            adLayerLayout.startAnimation(mOutAction);
                            Cache.getInstance().setHomeGreateAdClosed(true);
                        } else {
                            Intent intent = new Intent(getContext(), LoginActivity.class);
                            startActivityForResult(intent, CODE_REQUEST_LOGIN);
                        }
                    }
                }
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {


            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (!Cache.getInstance().isCityShow()) {
                    dyHeight += dy;
                    if (null != bottomAdBean && !TextUtils.isEmpty(bottomAdBean.getImageUrl()) && !Cache.getInstance().isHomeGreateAdClosed()) {
                        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                        int topPosition = layoutManager.findFirstVisibleItemPosition();
                        int height = recyclerView.getHeight();
                        if (dy > 0 && dyHeight >= height / 2 && adLayerLayout.getVisibility() != View.VISIBLE) {
                            adLayerLayout.setVisibility(View.VISIBLE);
                            adLayerLayout.startAnimation(mIntoAction);
                        } else if (dy < 0 && dyHeight < height / 2 && adLayerLayout.getVisibility() == View.VISIBLE) {
                            adLayerLayout.setVisibility(View.GONE);
                            adLayerLayout.startAnimation(mOutAction);
                        }
                    }

                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    int topPosition = layoutManager.findFirstVisibleItemPosition();
                    RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    View topView = layoutManager.findViewByPosition(topPosition);
                    if (null != topView && recyclerView.getChildViewHolder(topView) instanceof HomeLiveHolder) {
                        int bottom = topView.getBottom();
                        int height = topView.getHeight();
                        if (dy > 0) {
                            if (bottom < height * 1 / 10) {
                                HomeLiveHolder liveHolder = (HomeLiveHolder) recyclerView.getChildViewHolder(topView);
                                liveHolder.setLiveMute(true);
                                liveHolder.onIPause();
                            }
                        } else if (dy < 0) {
                            if (bottom > height * 1 / 10) {
                                HomeLiveHolder liveHolder = (HomeLiveHolder) recyclerView.getChildViewHolder(topView);
                                if (!liveHolder.isResuming()) {
                                    liveHolder.setLiveMute(true);
                                    liveHolder.onIResume();
                                }
                            }
                        }
                    }
                }
            }
        });

        adapter = new GreatestAdapter(getContext(), null, this, this);
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "首页"));
        pairs.add(new Pair<>("栏目", "精选"));
//            pairs.add(new Pair<>("行为类型", "点击"));
        adapter.setActiveClick(activeClick);
        adapter.setFragment(this);
        adapter.setPlayingListener(this);
        adapter.setPairs(pairs);
//        adapter.setAnchorListener(this);
//        adapter.setAnchorItemListener(this);
//        adapter.setEntranceClickListener(this);
        recyclerView.setAdapter(adapter);

    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        //JLog.e("HomeLiveHolder play onFragmentShow  ");
//        initLiveStatus(false);
        if (isFirst) {
            //首次显示的时候，自动刷新数据
            refreshLayout.autoRefresh();
        }
        if (adapter != null) {
            adapter.onResume();
            refreshPlayer();
        }
        JLog.e("okh  last time=" + lastGetTime);
        if (lastGetTime > 0) {
            long ca = SystemClock.elapsedRealtime() - lastGetTime;
            JLog.e("okh  will send msg  ca=" + ca);
            if (ca >= SPACE_GET_EXPRESS) {
                handler.sendEmptyMessage(WHAT_GET_EXPRESS);
            } else {
                handler.sendEmptyMessageDelayed(WHAT_GET_EXPRESS, SPACE_GET_EXPRESS - ca);
            }
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }


    private void parseMsg(Message msg) {
        if (msg.what == WHAT_GET_EXPRESS) {
            handler.removeMessages(WHAT_GET_EXPRESS);
            lastGetTime = SystemClock.elapsedRealtime();

            handler.sendEmptyMessageDelayed(WHAT_GET_EXPRESS, SPACE_GET_EXPRESS);
        } else if (msg.what == WHAT_GET_CLOSE_FAD) {
        }
    }

    /**
     * 获取精选模块 多个类型的显示数据。
     */
    private void getChannelList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            refreshLayout.refreshComplete();
            return;
        }
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                if (ListUtils.isListValued(focusColumns)) {
                    resetUrlTemps();
                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case GreatestAdapter.VIEWTYPE_BANNER:
                                    bannerUrlTemp = fc.getChannelUrl();
                                    break;
                                case GreatestAdapter.VIEWTYPE_EXPRESS:
                                    expressUrlTemp = fc.getChannelUrl();
                                    break;
                                case GreatestAdapter.VIEWTYPE_LIVE:
                                    liveUrlTemp = fc.getChannelUrl();
                                    break;
                                case GreatestAdapter.VIEWTYPE_NEWS_24:
                                    hour24UrlTemp = fc.getChannelUrl();
                                    break;
                                case GreatestAdapter.VIEWTYPE_POPULAR:
                                    popularUrlTemp = fc.getChannelUrl();
                                    break;
                                case GreatestAdapter.VIEWTYPE_PROMOTE:
                                    promoteUrl = fc.getChannelUrl();
                                    break;
                            }
                        }
                    }


                    lastGetTime = SystemClock.elapsedRealtime();
                    handler.removeMessages(WHAT_GET_EXPRESS);
                    handler.sendEmptyMessageDelayed(WHAT_GET_EXPRESS, SPACE_GET_EXPRESS);
                    getNewsArray(bannerUrlTemp, GreatestAdapter.VIEWTYPE_BANNER);
                    if (!Cache.getInstance().isCityShow()) {
                        getFloatAd();
                    } else {
                        adLayerLayout.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.refreshComplete();
            }
        });
    }


    @Override
    protected void onFragmentUnShowed(boolean isCallFromPause) {
        if (adapter != null) {
//            initLiveStatus(true);
            adapter.onPause();
            pauseLive();
        }
        handler.removeMessages(WHAT_GET_EXPRESS);
        super.onFragmentUnShowed(isCallFromPause);
    }

    @Override
    public void onPause() {
        if (adapter != null) {
            adapter.onPause();
            pauseLive();
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        if (adapter != null) {
            adapter.onDestory();
            adapter = null;
        }
        if (null != timer) {
            timer.cancel();
        }
        super.onDestroy();
    }


    /**
     * 首页浮层广告
     */
    private void getFloatAd() {
        SharedPreferencesUtil.setParam(getActivity(), FLOAT_AD_SHOW, false);

        String url = "/sctv/advert.json";
        NetUtils.getNetAdapter().getAdInfo(getOwnerName(), Constances.ST_BASE_URL + url, new AbsNetCallBack<AdvertDataVo>(AdvertDataVo.class) {
            @Override
            public void onSuc(AdvertDataVo advert) {
                if (ListUtils.isListValued(advert.getAdvertData())) {
                    List<AdvertBean> advertList = advert.getAdvertData();
                    AdvertBean advertBean = null;
                    for (int i = 0; i < advertList.size(); i++) {
                        if (advertList.get(i).getPosition() == 1) {
                            advertBean = advertList.get(i);//首页浮层广告
                        } else if (advertList.get(i).getPosition() == 2) {
                            bottomAdBean = advertList.get(i);
                        }
                    }
                    if (advertBean != null && isFirst && !Cache.getInstance().isStartAdClicked()) {
                        int count = (int) SharedPreferencesUtil.getParam(getActivity(), String.valueOf(advertBean.getVersionCode()), 0);
                        if ((advertBean.getShowCount() == 0 || count < advertBean.getShowCount()) && !TextUtils.isEmpty(advertBean.getImageUrl())) {
                            Intent intent = new Intent(getActivity(), FloatAdActivity.class);
                            intent.putExtra(BaseActivity.EX_DATA, advertBean);
                            startActivity(intent);
                            getActivity().overridePendingTransition(0, 0);
                        }
                    }
                    if (null != bottomAdBean && !TextUtils.isEmpty(bottomAdBean.getImageUrl())) {
                        GlideUtil.getGlid(getContext(), bottomAdBean.getImageUrl()).into(adLayer);
                    }
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                isFirst = false;
            }
        });

    }

    /**
     * 获取 精选-banner数据
     *
     * @param url
     * @param mode
     * @return
     */
    private boolean getNewsArray(String url, final int mode) {
        if (TextUtils.isEmpty(url)) {
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + url + "  mode=" + mode);
            return false;
        }
        if (!groupOrderHelper.addOne(mode)) {
            return false;
        }
        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), mode) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    HomeListItem hb = new HomeListItem();
                    hb.setNewsItemList(newsItems);
                    hb.setViewType(GreatestAdapter.VIEWTYPE_BANNER);
                    greatList.add(hb);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                groupOrderHelper.removeOne(mode);
                if (!Cache.getInstance().isCityShow()) {
                    getLiveArray(liveUrlTemp);
                } else {
                    getNews24Date(news24Domain);
                }
            }
        });
        return true;
    }

    /**
     * 获取精选--直播数据
     *
     * @param url
     * @return
     */
    private boolean getLiveArray(String url) {
        if (TextUtils.isEmpty(url)) {
            JLog.e("int " + this.getClass().getSimpleName() + " live url wrong ::" + url);
            return false;
        }
        if (!groupOrderHelper.addOne(GreatestAdapter.VIEWTYPE_LIVE)) {
            return false;
        }
        NetUtils.getNetAdapter().getLiveArray(getOwnerName(), url, new AbsListNetCallback<LiveItem>(ListTypeUtils.LiveItem()) {
            @Override
            public void onSuc(List<LiveItem> liveItems) {
                JLog.e("number ", "--------getLiveArray");
                if (ListUtils.isListValued(liveItems)) {
                    HomeLive hli = new HomeLive();
                    hli.setLiveList(liveItems);
                    hli.setViewType(GreatestAdapter.VIEWTYPE_LIVE);
                    greatList.add(hli);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                groupOrderHelper.removeOne(GreatestAdapter.VIEWTYPE_LIVE);

                //
                // 推荐成功后getNews24Date(news24Domain);
                //
                getNewsPromote(promoteUrl);
            }
        });
        return true;
    }


    /**
     * 获取 精选--视讯新闻数据
     *
     * @return
     */
    private boolean getNews24Date(final String news24Domain) {
        String news24Url = hour24UrlTemp;
        if (Cache.getInstance().isCityShow()) {
            news24Url = Cache.getInstance().getChoosedCityNewsUrl();
            newKey = GreatestAdapter.VIEWTYPE_LUZHOU_NEWS;
        }
        if (TextUtils.isEmpty(news24Url)) {
            JLog.e("int " + this.getClass().getSimpleName() + " 24h url wrong ::" + news24Url + "  page=" + current24Page);
            return false;
        }
        if (!groupOrderHelper.addOne(newKey)) {
            return false;
        }
        NetUtils.getNetAdapter().getNewsDateArray(getOwnerName(), news24Url, new AbsListNetCallback<NewsDate>(ListTypeUtils.NewsItem()) {
            private int te = 0;

            @Override
            public void onSuc(List<NewsDate> newsItems) {
                JLog.e("number ", "--------getNews24Date");
                if (ListUtils.isListValued(newsItems)) {
                    for (int i = 0; i < newsItems.size(); i++) {
                        newsItems.get(i).setNewsListUrl(news24Domain + newsItems.get(i).getNewsListUrl());
                    }
                    init24Helper().setDates(newsItems);

                    getNews24Page(news24Domain, true);
                }
            }

            @Override
            public List<NewsDate> doInBackground(List<NewsDate> newsDates) {
                if (ListUtils.isListValued(newsDates)) {
                    NewsDate stick = null;
                    if (newsDates.get(0).getNewsDate().equalsIgnoreCase("isStick")) {
                        stick = newsDates.get(0);
                        newsDates.remove(0);
                    }
                    if (newsDates.size() > 2) {
                        Collections.sort(newsDates, new NewsDateComparator());
                    }
                    if (null != stick) {
                        newsDates.add(0, stick);
                    }
                }
                return super.doInBackground(newsDates);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                groupOrderHelper.removeOne(newKey);
                super.onEnd();
            }
        });
        return true;
    }

    List<NewsItem> newsItemsList = new ArrayList<>();

    /**
     * 24小时新闻列表
     *
     * @param news24Domain
     * @param reset
     * @return
     */
    private boolean getNews24Page(final String news24Domain, final boolean reset) {
        if (!init24Helper().hasValuedDate()) {
            return false;
        }
        if (!groupOrderHelper.addOne(241)) {
            return false;
        }
        isReset = reset;
        hour24GetHelper.getNewsList(30, reset
                , new AbsListNetCallback<IListShowData>(IListShowData.class) {

                    @Override
                    public void onSuc(List<IListShowData> newsItems) {
                        if (ListUtils.isListValued(newsItems)) {
                            if (Cache.getInstance().isCityShow()) {
                                newsItemsList.clear();
                                for (int i = 0; i < newsItems.size(); i++) {
                                    IListShowData t = newsItems.get(i);
                                    if (t instanceof NewsItem) {
                                        NewsItem item = (NewsItem) newsItems.get(i);
                                        //外链h5等是绝对地址，不能再拼接。
                                        item.setNewsUrl(UrlUtils.linkUrls(news24Domain, item.getNewsUrl()));
                                        item.setNewsImage(UrlUtils.linkUrls(news24Domain, item.getNewsImage()));
                                        item.setLuzhouShow(true);
                                        if (item.getNewsType() == Constances.NEWS_TYPE_GRAPHIC ||
                                                item.getNewsType() == Constances.NEWS_TYPE_AUDIO ||
                                                item.getNewsType() == Constances.NEWS_TYPE_VIDEO ||
                                                item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                            newsItemsList.add(item);
                                        }

                                    }
                                }
                                greatList.addAll(newsItemsList);

                            } else {
                                setNewsData(newsItems, reset);
                            }
                        } else {
                            if (calledIndex <= 0) {
                                current24Page = calledIndex;
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        groupOrderHelper.removeOne(241);
                        if (Cache.getInstance().isCityShow()) {
                            isRefresh = false;
                            onNetFinish();
                        }
                    }
                });
        return true;
    }


    /**
     * 推荐新闻
     *
     * @return
     */
    private boolean getNewsPromote(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        if (!groupOrderHelper.addOne(GreatestAdapter.VIEWTYPE_PROMOTE)) {
            return false;
        }
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), url, 0, new AbsListNetCallback<NewsItem>(null) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (!ListUtils.isListValued(newsItems)) {
                    onError(null, null);
                    return;
                }
                NewsItem hli = newsItems.get(0);
                hli.setViewType(GreatestAdapter.VIEWTYPE_PROMOTE);
                greatList.add(hli);

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
            }

            @Override
            public void onEnd() {
                groupOrderHelper.removeOne(GreatestAdapter.VIEWTYPE_PROMOTE);
                getNews24Date(news24Domain);

            }
        });
        return true;

    }


    /**
     * 获取 精选--热门视频数据
     *
     * @param url
     * @return
     */
    private boolean getHomePopular(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        if (!groupOrderHelper.addOne(GreatestAdapter.VIEWTYPE_POPULAR)) {
            return false;
        }
        NetUtils.getNetAdapter().getHomePopular(getOwnerName(), url, new AbsNetCallBack<HomePopular>(HomePopular.class) {
            @Override
            public void onSuc(HomePopular homePopular) {
                //JLog.e("number ", "--------getHomePopular");
                if (homePopular != null && ListUtils.isListValued(homePopular.getNewsList())) {
                    HomeListItem hb = new HomeListItem();
                    hb.setNewsItemList(homePopular.getNewsList());
                    hb.setViewType(GreatestAdapter.VIEWTYPE_POPULAR);
                    hb.setSubUrl(homePopular.getMoreList());
                    Cache.getInstance().setHotVideoUrl(homePopular.getMoreList());
                    greatList.add(hb);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                groupOrderHelper.removeOne(GreatestAdapter.VIEWTYPE_POPULAR);
                List<NewsItem> li = new ArrayList<>();
                List<IListShowData> tempList = new ArrayList<>();
                int count = 0;
                int size = newsList.size();
                for (int i = 0; i < size; i++) {
                    if (newsList.get(0) instanceof NewsItem) {
                        count++;
                        NewsItem item = (NewsItem) newsList.get(0);
                        if (li.size() > 0) {
                            item.setAfterTitleMode(-1);//改变左侧时间线标识、行分割线的显示状态
                        } else {
                            item.setAfterTitleMode(2);//改变左侧时间线标识、行分割线的显示状态
                        }
                        li.add(item);
                    }
                    newsList.remove(0);
                    if (count == 3) {
                        break;
                    }
                }
//                tempList.addAll(newsList);
//                newsList.clear();
//                newsList.addAll(tempList);
                greatList.addAll(li);
                greatList.addAll(newsList);
                addListView();
//                getTimeLineList();
                onNetFinish();
                requestNewsClickCount(greatList, true);
            }
        });
        return true;
    }

    /**
     * 主播动态 数据请求（主播发表的内容）
     */
    private boolean getTimeLineList() {
        if (!groupOrderHelper.addOne(GreatestAdapter.VIEWTYPE_ANCHORS)) {
            return false;
        }
        JLog.e("--------------GreateFragment---getTimeLineList--start-");
        int index = 0;
        int ANCHOR_SCTV_TYPE = 0;
        HashMap<String, Object> param = new HashMap<>();
        param.put("anchorId", "");
        param.put("capacity", 1);
        param.put("index", index);
        param.put("requestType", ANCHOR_SCTV_TYPE);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("isTop", 1);//获取置顶的那一条主播动态
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        } else {
            param.put("userId", "");
        }
        String p = param.toString();
        JLog.e("-------------GreateFragment----getTimeLineList--p-  " + p);
        NetUtils.getNetAdapter().getTimelineList(getOwnerName(), param, new AbsListNetCallback<ADynamicsItem>(ADynamicsItem.class) {
            @Override
            public void onSuc(List<ADynamicsItem> anchortimelines) {
                JLog.e("----------GreateFragment-------getTimeLineList--onSuc-");
                if (ListUtils.isListValued(anchortimelines)) {
                    ADynamicsItem firstItem = anchortimelines.get(0);
                    firstItem.setDynamics(true);
                    firstItem.setSticky(true);
                    firstItem.setViewType(GreatestAdapter.VIEWTYPE_ANCHORS);
                    greatList.add(firstItem);
//                    dyDatas.addAll(0, anchortimelines);
//                    dataAddHelper.setUpDatas(getContext(), firstItem, GreatestAdapter.VIEWTYPE_ANCHORS);//暂时使用calledIndex来保存mode
                }

            }

            @Override
            public List<ADynamicsItem> doInBackground(List<ADynamicsItem> aDynamicsItems) {
                if (aDynamicsItems != null) {
                    for (ADynamicsItem item : aDynamicsItems) {
                        item.setViewType(AnchorHomePageAdapter.VIEWTYPE_DYNAMICS);
                    }
                }

                return super.doInBackground(aDynamicsItems);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                JLog.e("----------GreateFragment-------getTimeLineList--onError-errorMsg =" + errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                groupOrderHelper.removeOne(GreatestAdapter.VIEWTYPE_ANCHORS);
                if (null != newsList && newsList.size() > 1 && newsList.get(0) instanceof Titles) {
                    newsList.remove(0);
                }
                greatList.addAll(newsList);
                JLog.e("------------GreateFragment-----getTimeLineList--onEnd-");
                addListView();
            }


        });
        return true;

    }


    /**
     * 获取新闻列表点击量、评论数
     *
     * @param list
     * @param reset
     */
    private void setNewsData(List<IListShowData> list, final boolean reset) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            if (isRefresh) {
//                if (!Cache.getInstance().isCityShow()) {
////                    newsList.clear();
////                    List<NewsItem> li = new ArrayList<>();
////                    int count = 0;
////                    int size = newsItems.size();
////                    for (int i = 0; i < size; i++) {
////                        if (newsItems.get(0) instanceof NewsItem) {
////                            count++;
////                            NewsItem item = (NewsItem) newsItems.get(0);
////                            if (li.size() > 0) {
////                                item.setAfterTitleMode(-1);//改变左侧时间线标识、行分割线的显示状态
////                            }
////                            li.add(item);
////                        }
////                        newsItems.remove(0);
////                        if (count == 2) {
////                            break;
////                        }
////                    }
////                    newsList.addAll(newsItems);
//                    greatList.addAll(li);
//                } else {
                greatList.addAll(newsItems);
                requestNewsClickCount(greatList, true);
//                }
            } else {
                if (null != newsList && newsList.size() == 0 && null != newsItems && newsItems.size() > 1 && newsItems.get(0) instanceof Titles) {
                    newsItems.remove(0);
                }
//                greatList.addAll(newsItems);
                requestNewsClickCount(newsItems, reset);
            }
//            if (isRefresh) {
//                if (!Cache.getInstance().isCityShow()) {
//                    getHomePopular(popularUrlTemp);
//                }
//            }
            addListView();
            onNetFinish();

        }

    }

    /**
     * 获取新闻列表点击量、评论数
     *
     * @param list
     * @param reset
     */
    private void requestNewsClickCount(List<IListShowData> list, final boolean reset) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) instanceof NewsItem) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getUrlNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                }
            }
            if (ListUtils.isListValued(newsIdList)) {
                JLog.e("----------GreateFragment-------requestNewsClickCount--start-");
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        JLog.e("----------GreateFragment-------requestNewsClickCount--onSuc-");
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (newsItems.get(i) instanceof NewsItem) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else {
                                        if (countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        JLog.e("----------GreateFragment-------requestNewsClickCount--onEnd-");
                        if (isRefresh) {
                            greatList.clear();
                            greatList.addAll(newsItems);
                        } else {
                            if (null != newsItems && newsItems.size() > 1 && newsItems.get(0) instanceof Titles) {
                                newsItems.remove(0);
                            }
                            greatList.addAll(newsItems);
                        }
                        if (isRefresh) {
                            isRefresh = false;
                        }
                        onNetFinish();
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        JLog.e("------------GreateFragment-----requestNewsClickCount--onError-errorMsg=" + errorMsg);
                    }
                });
            }
        }
    }


    @Override
    public void OnLivePaly(String liveId) {
        if (!TextUtils.isEmpty(liveId)) {
            initViewClickData(liveId, 1);
        }
    }

    /**
     * 增加直播点击
     *
     * @param id
     * @param type（0.新闻 1.直播,2首页载入广告，3点击广告)
     */
    private void initViewClickData(final String id, int type) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", id);
        p.put("type", type);//type（0.新闻 1.直播,2首页载入广告，3点击广告)
        if (type != 2 && type != 3) {//广告相关点击量不传设备ID，不能防刷
            p.put("clientId", DeviceHelper.getInstance(this.getContext()).getDeviceId());//clientId设备id
        }
        NetUtils.getNetAdapter().addNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult vo) {
                JLog.e("initViewClickData", "GreatestFragment id = " + id + vo.isSuccess());
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });

    }

    private void addListView() {
        if (adapter != null) {
            adapter.setDatass(greatList);
        }
    }

    private synchronized void onNetFinish() {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        refreshLayout.setLoadMoreEnabled(hour24GetHelper != null && !hour24GetHelper.hasGetAll());

        if (adapter != null) {
            adapter.setDatass(greatList);
        }
        if (isReset) {
            isReset = false;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    recyclerView.smoothScrollToPosition(0);
////                    recyclerView.scrollTo(0,0);
//                    layoutManager.scrollToPositionWithOffset(0,0);
                }
            }, 700);
        }

    }

    private void resetUrlTemps() {
        bannerUrlTemp = null;
        expressUrlTemp = null;
        hour24UrlTemp = null;
        liveUrlTemp = null;
        popularUrlTemp = null;
        current24Page = -1;
        first24TitleDateTemp = null;
        secTitlePos = -1;
    }

    public void setSpecialUrlTemp(String specialUrlTemp) {
        this.specialUrlTemp = specialUrlTemp;
    }

    public void setAnchorsUrlTemp(String anchorsUrlTemp) {
        this.anchorsUrlTemp = anchorsUrlTemp;
    }

    /**
     * 切换是否显示泸州的新闻模式
     *
     * @param showLuZhou
     */
    public void setShowCityState(String showLuZhou) {
        if (!selectedCityName.equalsIgnoreCase(showLuZhou)) {
            //JLog.e("HomeLiveHolder play setShowCityState  selectedCityName ="+selectedCityName+"  showLuZhou = "+showLuZhou);
            selectedCityName = showLuZhou;
            greatList.clear();
            refreshLayout.autoRefresh();
        }
    }

    private BasePlayerView liveVideoView;

    public void initPlayer(BasePlayerView player) {
        if (null != player) {
            initVideoPlayer(player);
        }
    }

    /**
     * 快讯重磅跳转
     */
    OnItemInternalClick activeClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            HomeListItem homeListItem = null;
            if (view == null) {
                homeListItem = (HomeListItem) itemView.getTag(R.id.adapter_item_data_key);
            } else {
                homeListItem = (HomeListItem) itemView.getTag(R.id.adapter_item_data_key);
            }
            Intent intent = null;
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "精选"));
            pairs.add(new Pair<>("行为类型", "点击"));
            if (homeListItem.getSubType() == 1) {
                ((HomeFragment) getParentFragment()).setCurrentSelectIndex(0);
//                intent = new Intent(getContext(), MainActivity.class);
//                intent.putExtra(BaseActivity.EX_ID, homeListItem.getNewsItemList().get(position).getNewsId());
//                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                startActivity(intent);
                pairs.add(new Pair<>("位置", "快讯"));
            } else if (homeListItem.getSubType() == 2) {
                pairs.add(new Pair<>("位置", "重磅"));
                HashMap<String, String> map = new HashMap<>();
                for (Pair<String, String> p : pairs) {
                    map.put(p.first, p.second);
                }
                SkipUtil.skipWithNewsItem(getContext(), homeListItem.getNewsItemList().get(position), map);
            }
            GridsumWebDissector.getInstance().trackEvent(GreatestFragment.this, "", homeListItem.getNewsItemList().get(position).getNewsTitle(), "", 200, pairs);

        }
    };

//    public void setAnchorChannelUrl(String anchorChannelUrl) {
//        this.anchorChannelUrl = anchorChannelUrl;
//    }


    @Override
    public void OnSpecialSelectMore() {
        ((HomeFragment) getParentFragment()).setCurrentSpecialIndex();
    }


    @Override
    public void OnHotVideoSelect() {
        //跳转到短视频（随手拍）
    }


}
